package com.yaowk.authc.task;

import com.jfinal.plugin.activerecord.Db;
import com.yaowk.authc.Kit.ApplicationKit;
import com.yaowk.authc.model.OnlineCount;
import com.yaowk.authc.model.Platform;

import javax.servlet.ServletContext;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @authc yaowk
 * 2017/4/29
 */
public class RemberLoginTask implements Runnable {
    @Override
    public void run() {
        List<Platform> platformList = Platform.dao.findPlatform();
        ServletContext servletContext = ApplicationKit.getServletContext();
        List<OnlineCount> onlineCountList = new ArrayList<>();
        Date time = new Date();
        for (Platform platform : platformList) {
            OnlineCount onlineCount = new OnlineCount();
            Integer num = (Integer) servletContext.getAttribute(platform.getId().toString());
            if (num == null) {
                num = 0;
            }
            onlineCount.setNumber(num)
                    .setPlatformId(platform.getId())
                    .setTime(time);
            onlineCountList.add(onlineCount);
        }
        OnlineCount onlineCount = new OnlineCount();
        onlineCount.setNumber((Integer) servletContext.getAttribute("total"))
                .setPlatformId(-1)
                .setTime(time);
        onlineCountList.add(onlineCount);
        Db.batchSave(onlineCountList, onlineCountList.size());
    }
}
